//
//  HomeTableViewController.swift
//  weibo
//
//  Created by 崔顺建 on 16/8/7.
//  Copyright © 2016年 cui. All rights reserved.
//

import UIKit
//重用标记
private let ID = "cell"
class HomeTableViewController: VisitorTableViewController {
    
    private  var StatusViewModel: CSJStatusViewModel = CSJStatusViewModel()
    
    //风火轮
    private lazy var pullUpView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.redColor()
        return view
    }()
    //自定义下拉刷新
    private lazy var pullDownView: CZRefreshControl = {
        let pull = CZRefreshControl()
        
        pull.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
    
        return pull
    }()
    //系统的下拉刷新
    private lazy var refreshCtr: UIRefreshControl = {
        let crt = UIRefreshControl()
        crt.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        
    return crt
    }()
    
    @objc private func pullDownRefresh() {
    
    loadData()
    
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
        if isLogin {
            
            loadData()
            setupTable()
        }else {
            
            loainView?.updateVistorViewInfo(nil, imgName: nil)
            
        }
    }
    
    private func setupTable() {
        tableView.registerClass(CSJStatusTableViewCell.self, forCellReuseIdentifier: ID)
        //自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //预估行高
        tableView.estimatedRowHeight = 200
        //去分割线
        tableView.separatorStyle = .None
        //刷新控件
        tableView.tableFooterView = pullUpView
        
        //添加系统下拉刷新
        //self.refreshControl = refreshCtr
        //tableView.addSubview(refreshCtr)
        
        //自定义的控件
        tableView.addSubview(pullDownView)
        
        pullUpView.sizeToFit()
    }
    //tip动画lable
    private lazy var tipLable: UILabel = {
        let lable = UILabel(fontSize: 12, textColor: UIColor.whiteColor())
        lable.backgroundColor = UIColor.orangeColor()
        lable.text = "没有加载到微博数据"
        lable.textAlignment = .Center
         lable.hidden = true
        return lable
    }()
    
    //结束刷新
    private func endRefreshing() {
    
    pullUpView.stopAnimating()
     refreshCtr.endRefreshing()
        pullDownView.endRefreshing()
        
    }
    
    //添加控件设置约束
    private func setupUI() {
        if let nav = self.navigationController {
            tipLable.frame = CGRect(x: 0, y: CGRectGetMaxY(nav.navigationBar.frame) - 30, width: nav.navigationBar.width, height: 30)
            nav.view.insertSubview(tipLable, belowSubview: nav.navigationBar)
        
        }
        
    }
    //根据服务端返回数据显示tip
    private func startAnimation(message: String) {
        
        if tipLable.hidden == false {
        
        return
        }
        
        //显示视图文字
        tipLable.text = message
        tipLable.hidden = false
        UIView.animateWithDuration(1, animations: { () -> Void in
            
            self.tipLable.transform = CGAffineTransformMakeTranslation(0, self.tipLable.height)
            
            }) { (_) -> Void in
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.tipLable.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        self.tipLable.hidden = true
                })
        }
    
    }
    
    
    //加载微博数据
     private func loadData() {
        
        self.endRefreshing()
        StatusViewModel.loadData(pullUpView.isAnimating()) { (isSuccess ,message) -> () in
            
            if !self.pullUpView.isAnimating() {
                
                self.startAnimation(message)
                
            }
            

            
            
            
            if isSuccess {
                
                self.tableView.reloadData()
                
            } else {
                print("加载失败")
            }
        }
        
        
        //        CSJNetTools.sharedTools.requestNewStatus(CSJUserAccountViewModel.shardUserAccount.accessToken!) { (response, error) -> () in
        //            if error != nil {
        //            print("加载失败")
        //          return
        //            }
        //
        //            guard let dic = response as? [String :AnyObject] else {
        //            return
        //            }
        //           // 字典格式正确
        //            guard let dicArray = dic["statuses"] as? [[String :AnyObject]] else {
        //
        //            return
        //            }
        //            var tempArray = [StatusModel]()
        //
        //            for value in dicArray {
        //
        //            let status = StatusModel(dic: value)
        //
        //                tempArray.append(status)
        //            }
        //            self.statusList = tempArray
        //            self.tableView.reloadData()
        //        }
    }
}

extension HomeTableViewController {
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return StatusViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! CSJStatusTableViewCell
        cell.statusModel = StatusViewModel.statusList[indexPath.row]
        cell.selectionStyle = .None
        return cell
    }
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == StatusViewModel.statusList.count - 1 && !pullUpView.isAnimating() {
            pullUpView.startAnimating()
            loadData()
        }
    }
}













